//
//  EditTimerViewModel.swift
//  CrseAsst
//
//  Created by 申铭 on 2024/2/26.
//

import Foundation
import SwiftUI

class EditTimerViewModel: ObservableObject {
//    @Published var timer = CATimer()
//    
//    init() {
//        timer = CATimer()
//    }
    
    /// 时间段计时，设置开始结束时间
    func setStartAndEndTime(timer: CATimer, startTime: Date, endTime: Date) {
        var startTimestamp = kBaseTimestamp
        var endTimestamp = kBaseTimestamp
        
        var calendar = Calendar.current
        calendar.timeZone = TimeZone(identifier: "Asia/Beijing") ?? .current
        let startComp = calendar.dateComponents([.hour, .minute], from: startTime)
        let endComp = calendar.dateComponents([.hour, .minute], from: endTime)
        
        guard let sHour = startComp.hour,
                let eHour = endComp.hour,
                let sMinute = startComp.minute,
                let eMinute = endComp.minute else {
            return
        }
        
        
        let startTotalSeconds = (sHour * 60 * 60) + (sMinute * 60)
        
        /// 🌰例子：23:00 ~ 01:00
        /// 结束时间计算如下：
        /// 先算23:00 ~ 00:00的时间戳间隔
        /// 再加上00:00 ~ 01:00的时间戳间隔
        if sHour > eHour {
            startTimestamp = startTimestamp + Double(startTotalSeconds)
            
            let hourNum = 24 - sHour
            let seconds = (hourNum * 60 * 60) + (eHour * 60 * 60) + sMinute * 60 + eMinute * 60
            endTimestamp = startTimestamp + Double(seconds)
        } else {
            startTimestamp = startTimestamp + Double(startTotalSeconds)
            endTimestamp = endTimestamp + Double((eHour * 60 * 60) + (eMinute * 60))
        }
        
        log.verbose("startTimestamp:\(startTimestamp)")
        log.verbose("endTimestamp:\(endTimestamp)")
        
        timer.startTime = startTimestamp
        timer.endTime = endTimestamp
    }
}
